package itu.pw;

import java.io.*;

class HTMLlist {
    String str;
    HTMLlist next;

    HTMLlist(String s, HTMLlist n) {
        str = s;
        next = n;
    }
}

class Searcher {
    //////////////////////////////////////////////////////////////////////
    //
    // New method. Runs through a linked list of words contained within
    // HTML pages and searches for a specific word. Also prints out the
    // URLs of the pages where the given word was found
    //
    // Try searching for the word 'Links', it appears twice in the file
    // under 'http://www.it-c.dk/Internet' and
    // 'http://www.it-c.dk/Internet/sitemap'
    //
    //////////////////////////////////////////////////////////////////////
    public static String existsWithURLs(HTMLlist l, String word) {
        // Initialize variables
        String returnValue = "";
        String lastURL = "";
        boolean hasBeenAdded = false;

        // Search through the linked list
        while (l != null) {
            // Look for the "*PAGE:" pattern in the first 6 characters.
            // The substring method will fail if we don't check for words
            // smaller than 6 characters. This creates a bias towards pages
            // than have many words shorter than 6 characters
            if (l.str.length() >= 6 && l.str.substring(0, 6).equals("*PAGE:")) {
                // Yay! We found a URL, discard the identifier, extract
                // the page URL and update the last URL we encountered
                lastURL = l.str.substring(6);

                // Reset the flag to signal that the last URL we encountered
                // has not yet been added to our return string
                hasBeenAdded = false;
            } else if (l.str.equals(word)) {
                // Looks like we found the word we were searching for
                // If it has not yet been added to our return string...
                if (!hasBeenAdded) {
                    // ...we add it and set our flag to true. When a word
                    // is found more than once on a page, this ensures that
                    // the page URL is only added once
                    returnValue += "\t" + lastURL + "\n";
                    hasBeenAdded = true;
                }
            }

            // Get the reference to the next object in the linked list
            l = l.next;
        }

        return returnValue;
    }

    public static boolean exists(HTMLlist l, String word) {
        while (l != null) {
            if (l.str.equals (word))
                return true;

            l = l.next;
        }
        
        return false;
    }

    public static HTMLlist readHtmlList (String filename) throws IOException {
        String name;
        HTMLlist start, current, tmp;

        // Open the file given as argument
        BufferedReader infile = new BufferedReader(new FileReader(filename));

        name = infile.readLine(); //Read the first line
        start = new HTMLlist (name, null);
        current = start;
        name = infile.readLine(); // Read the next line

        while (name != null) {    // Exit if there is none
            tmp = new HTMLlist(name,null);
            current.next = tmp;
            current = tmp;            // Update the linked list
            name = infile.readLine(); // Read the next line
        }

        infile.close(); // Close the file
        return start;
    }
}

public class SearchCmd {
    public static void main(String[] args) throws IOException {
        String name;

        // Check that a filename has been given as argument
        if (args.length != 1) {
            System.out.println("Usage: java SearchCmd <datafile>");
            System.exit(1);
        }

        // Read the file and create the linked list
        HTMLlist l = Searcher.readHtmlList (args[0]);

        // Ask for a word to search
        BufferedReader inuser =
            new BufferedReader (new InputStreamReader (System.in));

        System.out.println ("Hit return to exit.");
        boolean quit = false;
        String URLsFound = "";
        
        while (!quit) {
            System.out.print ("Search for: ");
            name = inuser.readLine(); // Read a line from the terminal
            if (name == null || name.length() == 0) {
                quit = true;
            }
            // Store the return value in 'URLsFound' and if this variable
            // is not empty, we have found one or more URLs where 'name'
            // exists, so print the result to the console window
            else if (!((URLsFound = Searcher.existsWithURLs(l, name)).isEmpty())) {
                System.out.println("The word \"" + name + "\" has been found in the following URLs:");
                System.out.println(URLsFound);
            } else {
                System.out.println("The word \"" + name + "\" has not been found.");
            }
        }
    }
}